<?php
if (! defined ('IN_ZWS')) exit ();
// 全局变量
$userInfo = '';
$adminUid = '';
// 函数库
function setting($k, $v = null, $del = false) { // 参数二为空时获取设置，否则更新/插入设置
	$setting = M('Setting');
	$settinginfo = $setting -> where("k='" . $k . "'") -> find(); //查询是否已有该设置
	if ($settinginfo) {
		if ($del === true) return $setting -> where("k='" . $k . "'") -> delete();
		if ($v === null) {
			$rv = $setting -> where("k='" . $k . "'") -> find();
			return $rv['v']; // 如果v参数为空则返回该设置项
		}
		return ($setting -> where("k='" . $k . "'") -> save(array('v' => $v)) !== false); //如果存在则更新
	}
	return $setting -> add(array('k' => $k, 'v' => $v)); //如果不存在则插入
}

function fetchUrl($url, $timeout = 15, $formdata = array(), $cookie = '', $rejson = false) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($formdata));
	curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	$re = curl_exec($ch);
	curl_close($ch);
	if ($rejson) return @json_decode($re, true);
	return $re;
}

function checkQuick($limitTime = 2) {
	// 检查操作速度，防止恶意攻击
	if (empty($_SESSION['latime'])) {
		$_SESSION['latime'] = time();
		return false;
	}
	if (time() - $_SESSION['latime'] <= $limitTime) {
		$_SESSION['latime'] = time();
		return true;
	} else {
		$_SESSION['latime'] = time();
		return false;
	}
}

function sendMail($mailto, $mailsub, $mailbd) {
	import ('ORG.Util.SMTP');
	$mailSetting = json_decode(setting('mailSetting'), true);
	$mailsubject = "=?UTF-8?B?" . base64_encode($mailsub) . "?=";
	$smtp = new SMTP($mailSetting['host'], 25, true, $mailSetting['user'], $mailSetting['pass']);
	$smtp -> debug = false;
	$smtp -> sendmail($mailto, $mailSetting['address'], $mailsubject, $mailbd, 'HTML');
}

function sendVerifyMail($verifyinfo, $type, $mailto = '') {
	$siteName = setting('siteName');
	$sendtime = date ('Y年m月d日 H:m:s');
	$authlink = 'http://' . $_SERVER ['HTTP_HOST'] . __ROOT__ . '/index.php?m=u&a=verify&email=' . $verifyinfo ['email'] . '&authcode=' . $verifyinfo ['authcode'];
	switch ($type) {
		case 1 :
			$content = "<p>尊敬的{$verifyinfo['username']}，您好！</p><p>    感谢您注册著微帐号，请在120分钟内点击下面的链接以激活您的帐号：</p><p>    激活链接：{$authlink}</p><p>如果您没有注册却收到本邮件，请忽略。</p><p align='right'>{$siteName}<br>{$sendtime}</p>";
			$title = "[{$siteName}]请激活您的帐号";
			break;
		case 2 :
			$content = "<p>尊敬的{$verifyinfo['username']}，您好！</p><p>    您正在申请重置密码，请在120分钟内点击下面的链接以重置您的密码：</p><p>    验证链接：{$authlink}</p><p>如果您没有进行上述操作却收到本邮件，请忽略。</p><p align='right'>{$siteName}<br>{$sendtime}</p>";
			$title = "[{$siteName}]请验证您的操作";
			break;
		case 3 :
			$content = "<p>尊敬的{$verifyinfo['username']}，您好！</p><p>    您正在申请更换邮箱，需要进行两次验证操作，这是第一次，请在120分钟内点击下面的链接以完成第一次验证。单击该链接后，将往您之前填写的新邮箱发送第二封验证邮件，开始第二次验证。</p><p>    验证链接：{$authlink}</p><p>如果您没有进行上述操作却收到本邮件，请忽略。</p><p align='right'>{$siteName}<br>{$sendtime}</p>";
			$title = "[{$siteName}]请验证您的操作";
			break;
		case 4 :
			$content = "<p>尊敬的{$verifyinfo['username']}，您好！</p><p>    您正在申请更换邮箱，需要进行两次验证操作，这是第二次，请在120分钟内点击下面的链接以完成本次验证。单击该链接后，将成功更换您的邮箱。</p><p>    验证链接：{$authlink}</p><p>如果您没有进行上述操作却收到本邮件，请忽略。</p><p align='right'>著微用户中心<br>{$sendtime}</p>";
			$title = "[{$siteName}]请验证您的操作";
			break;
	}
	sendMail($mailto ? $mailto : $verifyinfo ['email'], $title, $content);
}

function getAvatarName() {
	return 'tmp' . time() . sprintf("%09d", $_SESSION['uid']);
}

function parseAvatar($avatarInfo = '', $size = 300) {
	if (empty($avatarInfo)) $avatarInfo = '0noavatar';
	$avatarSuffixType = substr($avatarInfo, 0, 1);
	$avatarNum = substr($avatarInfo, 1);
	switch ($avatarSuffixType) {
		case 0:
			$avatarSuffix = 'jpg';
			break;
		case 1:
			$avatarSuffix = 'png';
			break;
		case 2:
			$avatarSuffix = 'gif';
			break;
	}
	return __ROOT__ . '/Public/upload/avatar/' . $avatarNum . '_' . $size . '.' . $avatarSuffix;
}

function isAdmin($uid) {
	global $adminUid;
	if (empty($adminUid)) $adminUid = explode(',', setting('admin_uid'));
	return in_array($uid, $adminUid) ? true : false;
}

function cutStr($string, $length, $dot = ' ...') {
	if (strlen($string) <= $length) return $string;
	$pre = chr(1);
	$end = chr(1);
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);
	$strcut = '';
	$n = $tn = $noc = 0;
	while ($n < strlen($string)) {
		$t = ord($string[$n]);
		if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
			$tn = 1;
			$n++;
			$noc++;
		} elseif (194 <= $t && $t <= 223) {
			$tn = 2;
			$n += 2;
			$noc += 2;
		} elseif (224 <= $t && $t <= 239) {
			$tn = 3;
			$n += 3;
			$noc += 2;
		} elseif (240 <= $t && $t <= 247) {
			$tn = 4;
			$n += 4;
			$noc += 2;
		} elseif (248 <= $t && $t <= 251) {
			$tn = 5;
			$n += 5;
			$noc += 2;
		} elseif ($t == 252 || $t == 253) {
			$tn = 6;
			$n += 6;
			$noc += 2;
		} else {
			$n++;
		}
		if ($noc >= $length) break;
	}
	if ($noc > $length) $n -= $tn;
	$strcut = substr($string, 0, $n);
	$strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	$pos = strrpos($strcut, chr(1));
	if ($pos !== false) $strcut = substr($strcut, 0, $pos);
	return $strcut . $dot;
}

function isEmpty($var) {
	return empty($var); // PHP 5.4 以下版本的empty只能传变量，此为兼容模式
}
